package com.sign2024.sign2024project.test;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {
    private static final Map<String, WebSocketSession> usernameAndSessionMap = new HashMap<>();


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        System.out.println("-----------------------\npayload: " + payload);
        // 假设客户端发送的消息格式为 "register:username"
        if (payload.startsWith("register:")) {
            String username = payload.split(":")[1];
            usernameAndSessionMap.put(username, session);
        }
    }

    public void sendMessageToLocation(String location, String message) {

        WebSocketSession session = usernameAndSessionMap.get(location);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error("Error sending message to client: {}", e.getMessage());
            }
        }
    }

}
